package org.hzz.redis;

import lombok.Getter;
import redis.clients.jedis.ConnectionPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPooled;

import java.time.Duration;

/**
 * @author <a href="mailto:1193094618@qq.com">pkmer</a>
 * <br>
 * <a href = "https://gitee.com/developeros/videos-online">Code Repository</a>
 * At 2024/9/8
 */
public class JedisSupport {
    @Getter
    private JedisPooled jedisPool;
    public JedisSupport(String host,int port) {
        // JedisPooled does all hard work on fetching and releasing connection to the pool
        // to prevent connection starvation
        jedisPool = new JedisPooled(getJedisPoolConfig(), host, port,2000,null,8);
    }

    private ConnectionPoolConfig getJedisPoolConfig() {
        ConnectionPoolConfig poolConfig = new ConnectionPoolConfig();
        // maximum active connections in the pool,
        // tune this according to your needs and application type
        // default is 8
        poolConfig.setMaxTotal(500);

        // maximum idle connections in the pool, default is 8
        poolConfig.setMaxIdle(500);
        // minimum idle connections in the pool, default 0
        poolConfig.setMinIdle(500);


        // Enables waiting for a connection to become available.
        poolConfig.setBlockWhenExhausted(true);
        // The maximum number of seconds to wait for a connection to become available
        poolConfig.setMaxWait(Duration.ofSeconds(1));

        // Enables sending a PING command periodically while the connection is idle.
        poolConfig.setTestWhileIdle(true);
        // controls the period between checks for idle connections in the pool
        poolConfig.setTimeBetweenEvictionRuns(Duration.ofSeconds(1));
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        return poolConfig;
    }
}
